package controller;

import beans.LogEnum;
import beans.Model;
import beans.Task;
import dao.ModelDao;
import net.TaskOperator;
import net.sf.json.JSONObject;
import portal.controller.BaseServlet;
import utils.ExternalInterfaceParseUtil;
import utils.FileOper;
import utils.ParseUtil;
import utils.UserLogUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

public class CreateModelAndStartTask extends BaseServlet {
	@Autowired
	TaskOperator taskOperator ;
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String data = request.getParameter("data");
        JSONObject dataJson = JSONObject.fromObject(data);
        String userId = (String) request.getSession().getAttribute("userId");
        JSONObject modelJson = ParseUtil.generateModelJson(dataJson);
        Model model = new Model(dataJson.getString("name"),userId
                ,"",false,modelJson.toString(),"",false,"");
        List<Object> results = new ModelDao().addModelByModelReturnId(model);
        com.alibaba.fastjson.JSONObject result = new com.alibaba.fastjson.JSONObject() ;
        if(results.size()>0){
            int modelId = (int) results.get(0);
            model.setModelId(modelId);
            ExternalInterfaceParseUtil externalInterfaceParseUtil = new ExternalInterfaceParseUtil();
            Task task = externalInterfaceParseUtil.createTaskByModelAndParamsJson(userId,model,dataJson);
            task.setJson(FileOper.writeTaskJson(FileOper.genTaskJsonFilePath(), task.getJson()));
            String taskHash = UUID.randomUUID().toString().substring(0,20);
            result = taskOperator.saveAndStartTask(task,taskHash);
        }else{
            result.put("result",false);
            result.put("message","新增模型时出错");
        }
        response.getWriter().write(result.toString());
        // 日志记录
        UserLogUtil.dbLog(LogEnum.historyTask,
                LogEnum.createModelAndCreateTaskAndRunTask,
                userId,
                LogEnum.model.getValue()+"、"+LogEnum.task.getValue()+"名称："+model.getName()+"；");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
